package com.dianban.controller.nengliang;

import com.alibaba.fastjson.JSONObject;
import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.config.redis.RedisConstant;
import com.dianban.config.redis.RedisUtil;
import com.dianban.controller.BaseController;
import com.dianban.entity.FacePayConfig;
import com.dianban.entity.FacePayStoreOrder;
import com.dianban.entity.JwStore;
import com.dianban.entity.User;
import com.dianban.service.FacePayConfigService;
import com.dianban.service.FacePayStoreOrderService;
import com.dianban.service.JwStoreService;
import com.dianban.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(value = "ApiMapController", description = "地图控制器")
@RestController
@RequestMapping(value = "${interfacePath}/nengliang/map/")
public class ApiMapController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiMapController.class);

    @Autowired
    private FacePayStoreOrderService facePayStoreOrderService;
    @Autowired
    private JwStoreService storeService;
    @Autowired
    private FacePayConfigService facePayConfigService;

    @RequestMapping(value = "/checkStoreMatrix", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取检测门店跟我的距离")
    public ResultVo storeMatrix(String storeId, HttpServletRequest request, HttpServletResponse response) {
        logger.info("获取检测门店跟我的距离, storeId - {}", storeId);
        Boolean checkResult = false;
        try {
            if (StringUtils.isEmpty(storeId)) {
                return ResultVo.error(ResultCode.ERROR, "门店id不能为空");
            }
            String from = "";
            String ipAddr = IpUtils.getIpAddr(request);
            JSONObject location = TencentMapUtils.location(ipAddr);
            logger.info("当前ip地址：{}", location);
            if (location != null) {
                if (location.get("result") != null) {
                    JSONObject result = JSONObject.parseObject(String.valueOf(location.get("result")));
                    if (result != null) {
                        JSONObject _location = JSONObject.parseObject(String.valueOf(result.get("location")));
                        if (_location != null) {
                            //from = _location.get("lng") + "," + _location.get("lat");
                            from = _location.get("lat") + "," + _location.get("lng");
                        }
                    }
                }
            }
            logger.info("from:{}", from);
            //GlobalCoordinates source = null;
            //if (!StringUtils.isEmpty(from)) {
            //    source = new GlobalCoordinates(Double.valueOf(from.split(",")[1]), Double.valueOf(from.split(",")[0]));
            //}
            // 增加门店经纬度周边排序
            JwStore jwStore = storeService.findById(Long.valueOf(storeId));
            if (storeId == null) {
                return ResultVo.error(ResultCode.ERROR, "不存在该门店");
            }
            String matrixValue = "-1";
            if (!StringUtils.isEmpty(from)) {
                if (!StringUtils.isEmpty(jwStore.getLal())) {
                    //jwStore.setMatrix(JSONObject.toJSONString(TencentMapUtils.matrix(from, jwStore.getLal())));
                    //GlobalCoordinates target = new GlobalCoordinates(Double.valueOf(jwStore.getLal().split(",")[1]), Double.valueOf(jwStore.getLal().split(",")[0]));
                    //matrixValue = (String.valueOf(CaculateDistanceUtil.getDistanceMeter(source, target, Ellipsoid.Sphere)));
                    JSONObject jsonObject = TencentMapUtils.baiduTranslate(jwStore.getLal().split(",")[1] + "," + jwStore.getLal().split(",")[0]);
                    if (jsonObject != null) {
                        JSONObject matrix = TencentMapUtils.matrix(from, jsonObject.get("lat")+","+jsonObject.get("lng"));
                        if (matrix != null) {
                            if (matrix.get("distance") != null && !org.springframework.util.StringUtils.isEmpty(matrix.get("distance"))) {
                                matrixValue = JSONObject.toJSONString(matrix.get("distance"));
                            }
                        }
                    }
                }
            }
            logger.info("matrixValue:{}", matrixValue);
            List<FacePayConfig> facePayConfigList = facePayConfigService.find(60, 1, null);
            int count = 3;
            if (facePayConfigList != null && !facePayConfigList.isEmpty()) {
                count = Integer.valueOf(facePayConfigList.get(0).getValue());
            }
            if (Integer.valueOf(matrixValue) <= count) {
                checkResult = true;
            }
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(checkResult, "获取成功");
    }

    @RequestMapping(value = "/matrix", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取距离")
    public ResponseEntity matrix(String from, String to) {
        logger.info("请求获取距离, from - {}, to - {}", from, to);
        JSONObject matrix = new JSONObject();
        try {
            matrix = TencentMapUtils.matrix(from, to);
        } catch (Throwable e) {
            e.printStackTrace();
            return new ResponseEntity(matrix, HttpStatus.OK);
        }
        return new ResponseEntity(matrix, HttpStatus.OK);
    }

    // 腾讯地图根据ip获取定位信息
    @ApiOperation(notes = "location", httpMethod = "GET", value = "获取ip定位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
    })
    @RequestMapping(value = "location", method = RequestMethod.GET)
    public ResultVo location(HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        JSONObject location = new JSONObject();
        try {
            String ipAddr = IpUtils.getIpAddr(request);
            location = TencentMapUtils.location(ipAddr);
            logger.info("IP定位信息：{}", location);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(location, "获取成功");
    }

    // 腾讯地图根据经纬度获取定位信息
    @ApiOperation(notes = "getBylocation", httpMethod = "GET", value = "获取ip定位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
    })
    @RequestMapping(value = "getBylocation", method = RequestMethod.GET)
    public ResultVo getBylocation(String from, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        JSONObject location = new JSONObject();
        try {
            logger.info("经纬度定位-{}", from);
            location = TencentMapUtils.getLocation(from);
            logger.info("经纬度定位信息：{}", location);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(location, "获取成功");
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
    })
    @ResponseBody
    @ApiOperation(value = "测试数据")
    public ResultVo test(String userId, String storeId) {
        logger.info("请求测试数据,userId-{},storeId-{}", userId, storeId);
        List<FacePayStoreOrder> facePayStoreOrders = null;
        try {
            facePayStoreOrders = facePayStoreOrderService.findByParams(DateUtils.generateMonthDayBegin(), DateUtils.generateMonthDayEnd(), Long.valueOf(userId), Long.valueOf(storeId), "20", "20", "399");
            if (!CollectionUtils.isEmpty(facePayStoreOrders)) {
                return ResultVo.error(ResultCode.ERROR, "本月已购买过399套餐，无法再购买");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(facePayStoreOrders, "获取成功");
    }

}
